const {app, BrowserWindow, BrowserView, ipcMain, session, net, webContents, remote, Tray, Menu,dialog,shell} = require('electron')
const path = require('path')
const fs = require('fs');
const querystring = require('querystring');
// const {spawn, execFile} = require('child_process');
// const robot = require("robotjs");

const schedule = require("node-schedule");
const Base64 = require('js-base64').Base64;
const urlparse = require('url');
// const http = require('http');
// const https = require('https');
const logger = require('./logger')
const system = require('./system')
const httpServer = require('./httpServer')
const webSocketServer = require('./webSocketServer')
const netRequest = require('./netRequest')
const service = require('./service/service')
const userService = require('./service/userService')
// const exportUtils = require('./exportUtils')
const config = require('./config')


//全局变量区域,后面通过界面操作
let rootPath = path.resolve(__dirname);
var proxy = false;    //是否代理
var r_cookie = false;    //是否需要远程cookie
var check_task_timer = '*/10 * * * * *';
let devModel = true;
let token = '';  //登录token
let mainWindow = null;
// let mainWindow = null;
const WEBVIEW_TOP = 200;
const WEBVIEW_HEIGHT = 580;
const WEBVIEW_WIDTH = 1024;

let winPoolArray = [];
let checkTaskJob = null;
let monitorWinJob = null;

function start(options) {
    logger.info(`core start params=${options}`);

    rootPath = options['rootPath'] ? options['rootPath'] : rootPath;
    check_task_timer = options['check_task_timer'] ? options['check_task_timer'] : check_task_timer;
    // monitor_win_timer = options['monitor_win_timer'] ? options['monitor_win_timer'] : monitor_win_timer;
    devModel = options['devModel'] ? options['devModel'] : devModel;
    r_cookie = options['r_cookie'] ? options['r_cookie'] : r_cookie;
    proxy = options['proxy'] ? options['proxy'] : proxy;
    mainWindow = options['mainWindow'] ? options['mainWindow'] : mainWindow;

    // createTable();  //sqlite 初始化业务表

    startWebSocketServer(8765);

    startHttpServer(28081);

    let checkTaskRun = false;
    checkTaskJob = schedule.scheduleJob(check_task_timer, function () {
        console.debug("checkTaskJob start ...");
        if(checkTaskRun){
            console.warn("checkTaskJob still start ..." );
            return;
        }else{
            checkTaskRun = true;
        }
        try{
            // apiTaskService.replyTask();
        }catch (e) {
            console.error(e)
        }finally {
            checkTaskRun = false;
        }
    });



}



function startWebSocketServer(port){
    webSocketServer.startWebSocket(port,function(message,sid){
        //判断message 指令 做出相关动作 todo
        // debugger
        let res = JSON.parse(message);
        if(res.type == 'ping'){
           webSocketServer.sendMessage('pong','',sid);
        }else if(res.type == 'showOrHideWebview'){
            //获取webview
            var winObject = getWinObjectByWebContentsId(sid);
            if(!winObject){
                return;
            }
            let webview = winObject.webview;
            if(res.message.value){
                webview.setBounds({x: 0, y: WEBVIEW_TOP, width: WEBVIEW_WIDTH, height: WEBVIEW_HEIGHT})

            }else{
                webview.setBounds({x: 0, y: 0, width: WEBVIEW_WIDTH, height: 50})
            }
        }else if(res.type == 'collectStatus'){
            let collectStart = res.message.collectStart;  //todo 还需要刷新页面，看还要不要处理
            let processTask = getProcessTaskByWebContentsId(sid);
            if (processTask != null) {
                processTask.status = collectStart ? 1 : -1;
            }

        }
        // console.log(message);

    })

}

function startHttpServer(port) {
    //http server
    httpServer.startHttpServer(port, async function (options) {
        console.log('http options path:', options.path);
        let req = options.req;
        let res = options.res;
        let path = options.path;
        let jsonData = options.jsonData;
        // const parsedUrl = url.parse(req.url);
        // const path = parsedUrl.pathname;
        const query = options.query;
        let result = {success: true,message:'操作成功'}
        // const jsonData = JSON.parse(requestData);
        if (path.includes('/system/liveStatus')) {  //健康状态
            result.data = 'OK'
            //console.log('createWinWithProcessTask', activeProcessId)

        }else if (path.includes('/system/configList')) {
            result.data = service.configList();

        }else if (path.includes('/system/dataOptionList')) {
            result.data = service.dataOptionList();

        }else if (path.includes('/user/listAll')) {  //token 列表
            result.data = userService.list(query);
        }else if (path.includes('/user/list')) {  //token 列表
            result.data = userService.listByPage(query);
        }else if (path.includes('/user/save')) {  //token save
            result.data = userService.save(jsonData);
        }else if (path.includes('/user/update')) {  //token save
            result.data = userService.update(jsonData);
        }else if (path.includes('/user/del')) {  //token save
            result.data = userService.deleteById(jsonData);
        }else if (path.includes('loginSuccess')) {  //登录成功后
            token = jsonData.token;
        }else if(path.includes('/system/openExtUrl')){
            let extUrl = jsonData.extUrl;
            shell.openExternal(extUrl);
        }else{
            throw new Error("未找到该请求,"+path);
        }
        return result;

    })
}

//
function getWinObjectByWebContentsId(webContentsId) {
    let winObject = winPoolArray.find((item) => item['webContentsId'] == webContentsId);
    return winObject;
}
//


Array.prototype.remove = function (prop, value) {
    for (let i = 0; i < this.length; i++) {
        if (this[i][prop] === value) {
            this.splice(i, 1);
            i--; // 更新索引，以便继续遍历
        }
    }
};


Array.prototype.removeFirst = function (prop, value) {
    for (let i = 0; i < this.length; i++) {
        if (this[i][prop] === value) {
            return this.splice(i, 1)[0];
        }
    }
    return null;
};





function closeMainWindow(yesCallback,noCallback){
    // 显示确认对话框
    const choice = dialog.showMessageBoxSync(mainWindow, {
        type: 'question',
        buttons: ['是', '否'],
        title: '确认关闭',
        message: '您确认需要关闭吗？',
    });

    if (choice === 0) {
        // 用户点击 "是"，可以关闭窗口
        mainWindow = null;
        //向服务端提交close任务【并且是同步进行？】todo
        if(yesCallback){
            beforeCloseMainWindow(yesCallback);
        }

    } else {
        if(noCallback){
            noCallback();
        }
    }
}


function beforeCloseMainWindow(callback){
    if(checkTaskJob){
        checkTaskJob.cancel();
    }
    if(monitorWinJob){
        monitorWinJob.cancel();
    }
    webSocketServer.closeAll();
    callback();
}

function closeCollectWindow(winObject,event){
    //如果有正在 进行的任务，则提示
    let needTip = winObject.processTask && winObject.processTask.status == 1;
    if(needTip){
        // 显示确认对话框
        const choice = dialog.showMessageBoxSync(winObject.instance, {
            type: 'question',
            buttons: ['是', '否'],
            title: '确认关闭',
            message: '该有正在进行的任务，关闭窗口将终止任务，您确认需要关闭吗？',
        });

        if (choice === 0) {
            // 用户点击 "是"，可以关闭窗口
            beforeCloseCollectWindow(winObject);

        } else {
            // 阻止窗口关闭
            event.preventDefault();
        }
    }else{
        beforeCloseCollectWindow(winObject);
    }
}

function beforeCloseCollectWindow(winObject){
    webSocketServer.close(winObject.webContentsId);
    winPoolArray.removeFirst('id',winObject.id);

    //向服务端提交close任务【并且是同步进行？】todo
}



// 导出模块函数
module.exports = {
    start,
    closeMainWindow,

};
